package com.sky.web.app;

import com.sky.dto.DishPageDTO;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user/dish")
public class AppDishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品列表
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result findList(Long categoryId){ //1 接收参数
        //一: 先查redis缓存, 如果存有, 直接返回
        String key = "DISH:" + categoryId;
        if (redisTemplate.hasKey(key)) {
            log.info("redis缓存中存在数据");
            return Result.success(redisTemplate.opsForValue().get(key));
        }else {
            /// 二 : 如果redis缓存中没有数据, 查询数据库, 并将数据存入redis缓存中(同步缓存)
            //2 封装到dto中
            log.info("redis缓存中不存在数据,查询数据库");
            DishPageDTO dishPageDTO = DishPageDTO.builder()
                    .categoryId(categoryId)
                    .status(1)//默认启售
                    .build();

            //3 调用service
            List<DishVO> list = dishService.findList(dishPageDTO);
            //4 将数据存入redis缓存中(同步缓存)
            redisTemplate.opsForValue().set(key,list);
            //5 返回结果
            return Result.success(list);
        }
    }
}
